﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using Workflows.Components;
using Workflows.Components.Communication;

namespace Workflows.Designer
{
    public partial class EmailWorkflow : Form
    {
        private WorkflowDesign wfDesign;
        private Bitmap woxImg;

        public EmailWorkflow(WorkflowDesign wfDesign, Bitmap workflorImg)
        {
            InitializeComponent();
            this.woxImg = workflorImg;
            this.wfDesign = wfDesign;
        }

        private void EmailWorkflow_Load(object sender, EventArgs e)
        {
            this.pic_Workflow.Image = this.woxImg;
            this.txt_Subj.Text = this.wfDesign.WorkflowName;
            this.rt_Body.Text = "Attached is workflow " + this.wfDesign.WorkflowName;
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_To.Text))
            {
                string smtp = ConfigurationManager.AppSettings.Get("SmtpServer");
                string username = ConfigurationManager.AppSettings.Get("EmailUserName");
                string password = ConfigurationManager.AppSettings.Get("EmailPassword");
                bool needAuth = bool.Parse(ConfigurationManager.AppSettings.Get("RequireAuthentication"));
                bool reqSsl = bool.Parse(ConfigurationManager.AppSettings.Get("EnableSSL"));

                string myEmailAddr = string.Format("{0}@{1}.com", Environment.UserName, Environment.UserDomainName);
                EmailWorker emailWorker=new EmailWorker();
                EmailInstruction instruction = new EmailInstruction(
                    Guid.NewGuid(), Guid.NewGuid(), smtp, myEmailAddr,
                    this.txt_To.Text, this.txt_CC.Text, this.txt_Subj.Text, 
                    MailPriority.Normal, needAuth, username, password,
                    new string[] {this.wfDesign.DesignDocumentFilePath},
                    this.rt_Body.Text, this.ck_UseOutlook.Checked, 
                    reqSsl, null);
                emailWorker.SetInstruction(Guid.NewGuid(), instruction, "Email Worker",
                    "Email Component");
                try
                {
                    emailWorker.DoWork();
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}
